package servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.LoginDao;
import dao.LoginDaoImpl;

import model.Aluno;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Aluno aluno = new Aluno();
		if (request.getParameter("acao") != null){
			if (request.getParameter("acao").equals("login")) {
				if (request.getParameter("senha").trim().equals("")){
					primeiroAcesso(aluno, request, response);
				} else {
					aluno.setRa(request.getParameter("login").trim());
					aluno.setSenha(request.getParameter("senha").trim());
					acessar(aluno, request, response);
				}
			}
		}
	}
	
	private void primeiroAcesso(Aluno aluno, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}
	
	private void acessar(Aluno aluno,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LoginDao lDao = new LoginDaoImpl();
		boolean valido = false;
		String erro = "";
		try {
			valido = lDao.validaSenha(aluno);
		} catch (SQLException e) {
			erro = e.getMessage();
		}
		request.setAttribute("erro", erro);
		if (valido){
			request.setAttribute("user", 2);
		}
		RequestDispatcher view = request
				.getRequestDispatcher("index.jsp");
		view.forward(request, response);
	}
}
